<?php
/**
* Red RUgolok
* @version $Id: redrugolok.php
* @package RUgolok
* @subpackage redrugolok.php
* @author el_leo and manicon
* @copyright (C) el_leo and manicon, www.rugolok.de
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

global $mosConfig_debug, $mosConfig_lang, $mosConfig_livesite, $mosConfig_emailpass, $option, $task;

if($mosConfig_debug) {
	ini_set('display_errors',true);
	error_reporting(E_ALL);
}

/** @global mosMainFrame $mainframe
 *  @global mosUser $my
 *  @global gacl_api $acl
 *  @global stdClass $access
 */
global $access, $mainframe, $my, $acl;
$access = new stdClass();
$access->canEdit = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'all' );
$access->canEditOwn = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'own' );

require_once ( $mainframe->getPath( 'front_html' ) );

global $mosConfig_absolute_path;

$UElanguagePath=$mainframe->getCfg( 'absolute_path' ).'/components/com_redrugolok/language';
if (file_exists($UElanguagePath.'/'.$mosConfig_lang.'/'.$mosConfig_lang.'.php')) {
  include_once($UElanguagePath.'/'.$mosConfig_lang.'/'.$mosConfig_lang.'.php');
} else include_once($UElanguagePath.'/russian.php');

// Stylesheet der Komponente
$redrugolokPath = $mainframe->getCfg( 'relative_path' )."/components/com_redrugolok";
include_once($mainframe->getCfg( 'absolute_path' ).$redrugolokPath."/class/item.class.php");
include_once($mainframe->getCfg( 'absolute_path' ).$redrugolokPath."/class/item.class.html.php");
include_once($mainframe->getCfg( 'absolute_path' ).$redrugolokPath."/class/autoComplete.class.php");
include_once($mainframe->getCfg( 'absolute_path' ).$redrugolokPath."/functions.php");

// Fuege in den header ein
$mainframe->addCustomHeadTag("<link rel=\"stylesheet\" href=\"".$redrugolokPath."/redrugolok.css\" type=\"text/css\" />"); 
$mainframe->addCustomHeadTag("<script language=\"javascript\" type=\"text/javascript\" src=\"".$mosConfig_livesite."/includes/js/overlib_mini.js\"></script>");
$mainframe->addCustomHeadTag("<script language=\"javascript\" type=\"text/javascript\" src=\"".$mosConfig_livesite."/components/com_redrugolok/js/scriptaculous/lib/prototype.js\"></script>");
$mainframe->addCustomHeadTag("<script language=\"javascript\" type=\"text/javascript\" src=\"".$mosConfig_livesite."/components/com_redrugolok/js/scriptaculous/src/scriptaculous.js\"></script>");
$mainframe->addCustomHeadTag("<script language=\"javascript\" type=\"text/javascript\" src=\"".$mosConfig_livesite."/components/com_redrugolok/js/NiftyCube/niftycube.js\"></script>");
$mainframe->addCustomHeadTag("<script language=\"javascript\" type=\"text/javascript\" src=\"".$mosConfig_livesite."/components/com_redrugolok/js/mootools.js\"></script>");
$mainframe->addCustomHeadTag("<script src=\"".$redrugolokPath."/js/action.js\" type=\"text/javascript\"></script>");
$mainframe->addCustomHeadTag("<script src=\"".$redrugolokPath."/js/ajax.js\" type=\"text/javascript\"></script>");
$mainframe->addCustomHeadTag("<script src=\"".$redrugolokPath."/js/ajax-dynamic-list.js\" type=\"text/javascript\"></script>");

// was kommt als naechstes?
switch( $task ) {
	// Ein item/kreativ einfuegen
	case 'add':
		// Hole Typ aus dem POST
		add();
	break;

	case 'show':
		( isset( $_REQUEST['item_id'] ) ) ? ( $item_id = intval( mosGetParam( $_REQUEST, "item_id" ) )) : ( $item_id = null );
		if($item_id)
			showItem($item_id);
		else
			HTML_redrugolok::warning();
	break; 
	
	case 'editItem':
		( isset( $_REQUEST['item_id'] ) ) ? ( $item_id = intval( mosGetParam( $_REQUEST, "item_id" ) )) : ( $item_id = null );
		if($item_id)
			editItem($item_id);
		else
			HTML_redrugolok::warning();
		break;

	case 'showType':
		// Hole Typ aus POST
		( isset( $_REQUEST['id'] ) ) ? ( $type_id = intval( mosGetParam( $_REQUEST, "id" ) )) : ( $type_id = 0 );
		showType($type_id);
		break;

	case 'rate':
		rate();
		break;

	case 'listMy':
		listMy();
		break;

	case 'import':
		importRR();
		break;
		
	case 'comment':
		comment();
		break;

	// Hauptseite vom Red RUgolok
	default:
		redrugolok();
	break;

}

/**
 * Hauptseite vom Red RUgolok
 * Zeige als default
 */
function redrugolok() {
	global $database, $_REQUEST, $ueConfig, $my, $mainframe;
	$uid = $my->id;

	$mainframe->setPageTitle( _RR_TITLE_REDRUGOLOK );
	$mainframe->appendMetaTag( "keywords", _RR_KEYWORDS );
	$mainframe->appendMetaTag( "description", _RR_DESCRIPTION );

	HTML_redrugolok::redrugolok();
}


function comment(){
	global $database, $my;
	
	if(mosGetParam( $_REQUEST, "submit" ) and $my->id) {
		$item_id = intval( mosGetParam( $_REQUEST, "item_id" ) );
		$comment_text = mosGetParam( $_REQUEST, "comment_text" );
		$jos_user_id = $my->id;
		$comment_date = time();
		$query = "INSERT INTO #__redrugolok_comments ( id, item_id, jos_user_id, comment_text, comment_date) VALUES('', '".$item_id."', '".$jos_user_id."', '".$comment_text."', '".$comment_date."')";
		$database->setQuery($query);
		if(!$database->query())
			HTML_redrugolok::warning(_RR_COMMENT_ERROR." ".$database->getErrorMsg());
	}
	showItem($item_id);
}

/**
 * Zeige ein Item
 * @param int $item_id ID Nummer des Items
 */
function showItem($item_id) {
	global $database, $my, $mainframe;

	$item = new Item($item_id);
	//$item->$this->init();
	//$item->$this->setAuthors();
	if($item->id > 0) {
		$mainframe->setPageTitle( _RR_TITLE_SHOW." ".$item->title."" );
		$mainframe->appendMetaTag( "keywords", $item->keywords );
		$mainframe->appendMetaTag( "description", $item->description );

		HTML_item::show(&$item);
		//HTML_redrugolok::showRatings(&$item);
		HTML_redrugolok::showComments($item_id);
	} else
		echo HTML_redrugolok::warning(_RR_NO_ITEM);
}

/**
 * Liste alle meine Items
 */
function listMy() {
	global $database, $my, $mainframe;


}

/**
 * Zeige Items einer Kategorie
 * @param int $type_id ID Nummer des Items
 */
function showType($type_id) {
	global $database, $Itemid;

	$query = "SELECT * FROM #__redrugolok_types WHERE id = '".$type_id."'";
	$database->setQuery($query);
	$type = null;
	$database->loadObject($type);

	// New items
	$query = "SELECT * FROM #__redrugolok_items WHERE type_id = '".$type_id."'" .
			"ORDER BY id DESC LIMIT 0,3";
	$database->setQuery($query);
	$item_list_new = $database->loadObjectList();

	// Top rated
	$query = "SELECT * FROM #__redrugolok_items WHERE type_id = '".$type_id."'" .
			"ORDER BY points DESC LIMIT 0,3";
	$database->setQuery($query);
	$item_list_top = $database->loadObjectList();

	// all items
	$query = "SELECT * FROM #__redrugolok_items WHERE type_id = '".$type_id."'";
	$database->setQuery($query);
	$item_list = $database->loadObjectList();

	// template
	HTML_redrugolok::showType($type, $item_list_new, $item_list_top, $item_list);

}

	/**
	 * Gets the name of type by ID number <var>$id</var>
	 *
	 * @param int $id ID number of a type
	 * @return Object
	 *
	 */
	function getItemType( $id ) {
		global $database;

		$type = null;
		$query = "SELECT * FROM #__redrugolok_types WHERE id = '".$id."'";
		$database->setQuery( $query );

		if ( $database->loadObject( $type ) ) {
			return $type;
		} else
			return null;
	}


/**
 * Fuege ein Item in die Datenbank
 * Falls nicht authorisiert, dann wird default Funktion angezeigt.
 * Es wird zuerst ein Itemtyp ausgewaehlt. Dann je nach Typ, wird eine eigene Funktion dargestellt.
 * TODO: Behandlung von "rated"
 */
function add() {
	global $my, $mainframe, $type_id;
	$mainframe->setPageTitle( _RR_TITLE_ADD );
	$uid = $my->id;

	// Hier hast du nichts zu suchen, bitte registrieren :)
	if ( $uid == 0 ) {
		HTML_redrugolok::NotAuth();
		return;
	}

	// Was wurde auf der vorherigen Seite ausgefuellt?
	switch( $_POST["submited"] ) {
		// falls Formular "selectType" versendet wurde, dann f�lle das Item naechste aus
		// speichern
		case "fillOut":
			if( !checkID( mosGetParam( $_POST, 'checkID' ) ) ) {
			$item = new Item();

			// Fill required and optional fields
			/*$item->title = mosGetParam( $_POST, 'title' );
			$item->type_id = intval( mosGetParam( $_POST, 'type_id' ) );
			$item->description = mosGetParam( $_POST, 'description' );
			$order   = array("\r\n", "\n", "\r");
			$replace = '<br />';
			$item->text = str_replace($order, $replace, $_POST['text']);
			$item->filename = mosGetParam( $_POST, 'filename' );
			$item->group_id = intval( mosGetParam( $_POST, 'group_id' ) );
			$item->mood_id = intval( mosGetParam( $_POST, 'mood_id' ) );
			$item->keywords = mosGetParam( $_POST, 'keywords' );
			$item->inspired_by = mosGetParam( $_POST, 'inspiredby' );
			$item->published = intval( mosGetParam( $_POST, 'showme' ) );
			$item->rated = 1;

			if (is_array(mosGetParam( $_POST, 'authors' ))) {
				foreach(mosGetParam( $_POST, 'authors' ) as $author) {
					$authors[] = intval($author);
					$item->authors = $authors;
				}
			} else {
				$authors[] = intval( mosGetParam( $_POST, 'authors' ) );
				$item->authors = $authors;
			}
			
			$item->date = time();
			$item->checkID = mosGetParam( $_POST, 'checkID' ) ;
			
			

			if( !$item->insert() ) {
				HTML_redrugolok::warning( $item->error, 0 );
				$item = new Item( );
				$item->type_id = intval( $type_id );
				$item->setTypeName();
				HTML_redrugolok::fillOut( &$item );
			}
			else {
				HTML_redrugolok::insert_success(&$item);
			}
			*/
			
			print_r($_POST);
		}
		break;
		// Sonst Typ auswaehlen
		default:
			$item = new Item( '' );
			HTML_redrugolok::fillOut( &$item );
	}
}



/*
 * Bearbeite ein Item
 */
function editItem($item_id) {
	global $mainframe;
	$mainframe->setPageTitle( _RR_EDIT_ITEM );

	$item = new Item($item_id);
	if (isset($_POST["submited"]) and $_POST["submited"]) {
		update($item_id);
	} else {
		HTML_redrugolok::editItem( &$item );
	}
}

/**
 * Speichere einen Eintrag
 */
function update($item_id) {
	global $database;
	$item = new Item($item_id);

	// Fill required and optional fields
	$item->title = mosGetParam( $_POST, 'title' );
	$item->type_id = intval( mosGetParam( $_POST, 'type_id' ) );
	$item->description = mosGetParam( $_POST, 'description' );
	$item->text = mosGetParam( $_POST, 'text' );
	$item->filename = mosGetParam( $_POST, 'filename' );
	$item->group_id = intval( mosGetParam( $_POST, 'group_id' ) );
	$item->mood_id = intval( mosGetParam( $_POST, 'mood_id' ) );
	$item->keywords = mosGetParam( $_POST, 'keywords' );
	$item->inspired_by = mosGetParam( $_POST, 'inspiredby' );
	$item->authors = mosGetParam( $_POST, 'authors' );
	$item->rated = 1;
	( intval( mosGetParam( $_POST, 'showme' ) ) ) ? ( $item->published = 1 ) : ( $item->published = intval( mosGetParam( $_POST, 'showme' ) ) );
	$item->last_update = time();

	if( !Item::update(&$item) )
		HTML_redrugolok::warning( $item->error, 0 );
	else
		HTML_redrugolok::update_success(&$item);
		
	return 0;
}


/**
 * Stellt sicher ob es schon ein Item in der DB mit der Checksumme vorhanden ist,
 * um die Doppeleintraege zu vermeinden und die ID des eingefuegten Items zu ermitteln. Dann wird die
 * Beziehung Item-Autor in die DB geschrieben
 *
 * @param String $value Aus dem Zeitstempel in MD5 kodierte Zeichenfolge
 * @return int Falls es noch kein Eintrag vorhanden ist wird eine '0' zurueckgegeben, anderfalls '1'
 */
function checkID($value) {
	global $database;
	if(preg_match('/^[a-f0-9]{32}$/', $value)) {
		$item = null;
		$query = "SELECT checkID FROM #__redrugolok_items WHERE checkID = '".$value."'";
		$database->setQuery( $query );
		$database->loadObject($item);

		if( $item->checkID == $value ) {
			HTML_redrugolok::warning();
			return 1;
		} else return 0;

	} else {
		// Checksumme wurde manipuliert oder ist fehlerhaft
		HTML_redrugolok::warning();
		return 1;

	}
}

/**
 * Hole alle vorhanden Typen aus der DB
 * Falls ein Filter <var>$filter</var> uebergeben wurde,
 * dann wird dieses in der Query beruecksichtigt
 * @param $filter String
 * @return Object Ein Objekt oder eine Liste von Objekten
 */
function getTypes( $filter = 1 ) {
	global $database; 

	$database->setQuery( "SELECT * FROM #__redrugolok_types WHERE ".$filter."" );

	if($types = $database->loadObjectList()) {
		return $types;
	} else
		die("No types defined");
}


/**
 * Zeige Item des Tages
 */
function itemOfTheDay() {
	global $database;

	$item = new Item(29);
	HTML_redrugolok::itemOfTheDay( $item );
}

/*
 * listRatings
 */

function listRatings(){
	HTML_redrugolok::listRatings();
}

/**
 * Liste alle
 */
function listTypes() {
	$types = getTypes();
	HTML_redrugolok::listTypes($types);

}

/**
 * List new items
 */
function listNew(){
	global $database;

	$query = "SELECT * FROM #__redrugolok_items LIMIT 1,5";
	$database->setQuery( $query );
	$items = $database->getObjectList();

	foreach($items as $item) {
		$item->setAuthors();
	}

	HTML_redrugolok::listNew($items);
}



/**
 * Zugriff verweigert
 * Nicht angemeldete Person auffordern sich einzuloggen oder zu registrieren.
 * @return String Warnmeldung oder Hinweis
 */
function NotAuth() {
	global $database, $mainframe, $my;
	$mainframe->setPageTitle( _RR_TITLE_NOTAUTH );

	if( !$my->id ) {
		$query = "SELECT introtext FROM #__content WHERE title = 'redrugolokNotAuth'";
		$database->setQuery($query);
		$database->query($query);
		$content = null;
		$database->loadObject($content);
		return $content->introtext;
	} else return _RR_NOTAUTH;
}

?>
